class Solution
{
public:
    vector<vector<int>> getAncestors(int n, vector<vector<int>> &edges)
    {
        vector<vector<int>> parents(n);
        for (auto &edge : edges)
        {
            parents[edge[1]].push_back(edge[0]);
        }
        vector<vector<int>> result;
        for (int i = 0; i < n; ++i)
        {
            set<int> ans;
            queue<int> q;
            q.push(i);
            while (!q.empty())
            {
                int node = q.front();
                q.pop();
                for (int p : parents[node])
                {
                    if (!ans.count(p))
                    {
                        q.push(p);
                        ans.insert(p);
                    }
                }
            }
            result.emplace_back(ans.begin(), ans.end());
        }
        return result;
    }
};